package com.apkicon.core;

import com.apkicon.model.ApkInfo;
import com.apkicon.model.IconInfo;
import com.apkicon.parser.ApkParserLibrary;
import com.apkicon.processor.IconProcessor;
import com.apkicon.processor.PngIconProcessor;
import com.apkicon.processor.VectorIconProcessor;
import com.apkicon.processor.AdaptiveIconProcessor;
import com.apkicon.fallback.BundletoolIconExtractor;

import java.io.File;
import java.util.Map;

/**
 * APK图标提取器主类
 * 按照Android原生原理解析和提取图标
 */
public class ApkIconExtractor {
    
    private final Map<String, IconProcessor> processors;
    private final BundletoolIconExtractor bundletoolExtractor;
    
    public ApkIconExtractor() {
        this.processors = Map.of(
            "png", new PngIconProcessor(),
            "webp", new PngIconProcessor(),
            "xml", new VectorIconProcessor(),
            "vector", new VectorIconProcessor(),
            "adaptive", new AdaptiveIconProcessor(),
            "bitmap", new PngIconProcessor(),
            "shape", new VectorIconProcessor()
        );
        this.bundletoolExtractor = new BundletoolIconExtractor();
    }
    
    /**
     * 从APK文件中提取图标
     * @param apkFile APK文件
     * @param targetSize 目标尺寸
     * @return 图标信息
     */
    public IconInfo extractIcon(File apkFile, int targetSize) throws Exception {
        try {
            // 首先尝试使用内置解析器（按照Android原生原理）
            return extractIconWithParser(apkFile, targetSize);
        } catch (Exception e) {
            System.err.println("Primary APK parser failed: " + e.getMessage());
            
            // 如果内置解析器失败，尝试使用bundletool作为fallback
            if (bundletoolExtractor.isBundletoolAvailable()) {
                System.out.println("Trying bundletool as fallback...");
                IconInfo fallbackIcon = bundletoolExtractor.extractIconWithBundletool(apkFile, targetSize);
                if (fallbackIcon != null) {
                    System.out.println("Successfully extracted icon using bundletool");
                    return fallbackIcon;
                }
            } else {
                System.err.println("Bundletool is not available");
            }
            
            // 如果所有方法都失败，抛出原始异常
            throw e;
        }
    }
    
    /**
     * 使用apk-parser库提取图标
     */
    private IconInfo extractIconWithParser(File apkFile, int targetSize) throws Exception {
        // 使用apk-parser库解析APK
        ApkParserLibrary.ApkInfo apkInfo = ApkParserLibrary.parseApkWithLibrary(apkFile);
        
        // 根据图标类型选择处理器
        IconProcessor processor = getProcessor(apkInfo.getIconType());
        
        // 显示处理方式
        String processingMethod = getProcessingMethod(apkInfo.getIconType());
        System.out.println("🔧 处理方式: " + processingMethod);
        
        // 处理图标
        return processor.processIcon(apkInfo, apkInfo.getIconResource(), targetSize);
    }
    
    /**
     * 获取图标处理器
     */
    private IconProcessor getProcessor(String type) {
        IconProcessor processor = processors.get(type);
        if (processor == null) {
            throw new UnsupportedOperationException("Unsupported icon type: " + type);
        }
        return processor;
    }
    
    /**
     * 获取处理方式描述
     */
    private String getProcessingMethod(String type) {
        switch (type) {
            case "png":
                return "直接使用PNG图标";
            case "webp":
                return "直接使用WebP图标";
            case "xml":
            case "vector":
                return "Vector Drawable渲染";
            case "adaptive":
                return "Adaptive Icon渲染";
            case "bitmap":
                return "Bitmap Drawable渲染";
            case "shape":
                return "Shape Drawable渲染";
            default:
                return "未知处理方式";
        }
    }
    
    /**
     * 检查bundletool是否可用
     */
    public boolean isBundletoolAvailable() {
        return bundletoolExtractor.isBundletoolAvailable();
    }
}